<template>
	<view class="m-agent-chat cover-screen-position flex-column-start-center"
		:style="{backgroundImage:'url('+bgUrl+')'}" @click="handleGlobalClick">
		<view class="top-box" :style="{height:topBoxHeight+'rpx'}"></view>
		<view class="task-info flex-row-center-center">
			<view class="task-info-content flex-column-center-center">
				<view class="info-top flex-row-start-center">
					<view class="info-icon flex-row-center-center">剧情挑战</view>
					<view class="info-round flex-row-start-center">
						<view class="info-text">轮次</view>
						<view class="info-round-progress">
							<view class="progress-inner"></view>
							<view class="progress-text">2/10</view>
						</view>
					</view>
				</view>
				<view class="info-target flex-row-start-center">
					目标：气走李瑶，为他解围
				</view>
			</view>
		</view>
		<view class="talk-log-input flex-column-start-center">
			<!-- :style="{'margin-bottom':testBottom+'rpx'}" -->
			<view class="talk-list-box">
				<scroll-view ref="talkListScollView" scroll-y class="scroll-content" :scroll-into-view="scrollToId"
					:show-scrollbar="false" :scroll-with-animation="true">
					<view class="talk-item flex-row-center-center">
						<view class="talk-item-text talk-item-text-intro">
							<text
								class="intro-tip-text">背景介绍：</text>你在上班的路上突然被总裁沈亦凌搂腰拉入怀中，气得他对面的李瑶不停跺脚。这个李瑶是公司大股东的女儿，一直在坚持不懈的追求沈亦凌。你还没反应过来，沈亦凌冰凉的嘴唇就贴上了你的耳朵。
						</view>
					</view>
					<view class="talk-item" :class="{'flex-row-end-start':item.my,'flex-row-start-start':!item.my}"
						v-for="(item,index) in testList" :id="'talk-item-'+index" :key="index">
						<view class="talk-item-avatar" v-if="!item.my">
							<image class="cover-img avatar-img"
								src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/03efd458890f4d058571e7d08eccacd8.jpg"
								mode="aspectFill"></image>
						</view>
						<view class="talk-item-text "
							:class="{'talk-item-text-user':item.my,'talk-item-text-npc':!item.my}">
							<!-- 	<view class="vioce-box flex-row-center-center" id="voice-box" >
									<view class="voice-icon flex-row-center-center" id="voice-icon">
										<image class="cover-img"
											src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/35d05201acec42e2ad51444eb2c5835b.png"
											mode="aspectFill" id="voice-img"></image>
									</view>
									<text class="voice-text" id="voice-text">6"</text>
							
								</view> -->
							{{item.replyText}}
						</view>
					</view>




				</scroll-view>
			</view>
			<view id="input-box" class="input-box flex-row-start-center"
				:style="{'margin-bottom':keyBordHeight+'rpx',height:inputContentHeight+'rpx'}" @click.stop>
				<view class="input-content flex-row-center-center" id="input-content">
					<view class="input-area flex-row-start-center">
						<view class="input-area-inner">
							<input v-model="messageText" type="text" placeholder-style="color:rgba(255,255,255,.6);"
								placeholder="说点什么..." confirm-type="send" :adjust-position="false"
								@keyboardheightchange="handleKeyBoardHeightChange" @focus="inputFocus" @blur="inputBlur"
								@confirm="inputConfirmMessage" class="input-inner" :focus="inputIsFocus" />
						</view>
						<view class="input-magic-icon" @click="handleMagicIconClick">
							<image v-show="!isShowMagic" class="cover-img"
								src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/47478b96b069484bad294de592bb070d.png"
								mode="aspectFill"></image>
							<image v-show="isShowMagic" class="cover-img"
								src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/037e1b6ebfdd4491ab6cd7819a644bf6.png"
								mode="aspectFill"></image>
						</view>

					</view>
					<view class="input-control-icon flex-row-center-center" @click="handleControlIconClick">

						<image class="input-add-icon" :class="{'control-icon-rotate':isMoreControlShow}"
							v-show="controlIconType=='more'" :src="moreControlIcon" mode="aspectFill"></image>
						<view class="input-send-icon" v-show="controlIconType=='send'">
							<image class="cover-img"
								src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/8a35f27611d9488f92268581ab311805.png"
								mode="aspectFill"></image>
						</view>
					</view>
				</view>

				<view class="input-bg-box flex-column-start-center" id="input-bg" :style="{height:bgBoxHeight+'rpx'}">
					<view class="bg-top-box"></view>
					<view class="bg-bottom-box"></view>
				</view>

				<view class="input-operate-box flex-column-start-center"
					:style="{top:inputContentHeight+'rpx',height:buttonBoxHeight+'rpx'}" v-if="isShowMagic">
					<view class="operate-tip flex-row-start-center">选中你想说的</view>
					<view class="magic-tip-box">
						<scroll-view ref="magicTipsScrollView" scroll-y class="scroll-content" :show-scrollbar="false"
							:scroll-with-animation="true">
							<view class="magic-tip-list">
								<view class="magic-tip-item" v-for="(item,index) in magicTipList" :key="index">{{item}}
								</view>
							</view>

						</scroll-view>
					</view>

				</view>

				<view class="input-control-btns flex-column-start-center"
					:style="{top:inputContentHeight+'rpx',height:buttonBoxHeight+'rpx'}" v-if="isMoreControlShow">
					<view class="control-btn-list-box flex-row-start-start">
						<scroll-view ref="controlBtnsScrollView" scroll-y class="scroll-content" :show-scrollbar="false"
							:scroll-with-animation="true">
							<view class="control-btn-list flex-row-start-start">
								<view class="control-btn-item flex-row-center-center"
									:class="{'click-style':index == actClickIndex}" v-for="(item,index) in controlBtns"
									:key="index" @click="handleControlBtnClick(item,index)">
									<image class="btn-icon" :src="item.image" mode="aspectFill"></image>
									<view class="btn-name flex-row-center-center">{{item.name}}</view>
								</view>
							</view>
						</scroll-view>
					</view>


				</view>


			</view>
		</view>


	</view>
</template>

<script>
	import {
		chatInit,
		sentMessage,
		getChatMessageList
	} from "@/api/game.js"
	export default {
		props: {
			agentId: {
				type: String,
				default: ""
			},
			gameId: {
				type: String,
				default: ""
			}
		},
		data() {
			return {
				// 对话消息部分
				params: {
					//搜索条件
					chatId: '',
					pageSize: 10,
					pageNumber: 1,
				},
				gameChat: null,
				chatId: null,
				msgList: [],
				// 输入框部分
				messageText: "",
				inputIsFocus: false,

				//魔法棒部分
				isShowMagic: false,
				magicTipList: [
					"(托腮微笑)你的梦想很manly，和你的人一样酷呢。",
					"(轻轻叹气)原来我们有共同点，我也想守护在乎的人。",
					"(看着他,眼里闪烁着光)如果梦想能让人变得温柔，那它就伟大。",

				],
				// 更多操作部分
				clickTimeOutId: null,
				actClickIndex: -1,
				controlBtns: [{
					name: "重启",
					image: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/41bc7871040d4d0287211efc73ab2d60.png",
					type: "restart"
				}, ],
				// 
				isMoreControlShow: false,
				controlIconType: 'more', //more 更多操作  send 发送消息
				inputContentHeight: 120,
				keyBordHeight: 0,
				bgBoxHeight: 300,

				// 基础属性
				buttonBoxHeight: 500, // 更多、魔法棒盒子高度
				screenWidth: 375,
				topBoxHeight: 170,
				bgUrl: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/1d9c202963234e309f8fec36c94f55a4.jpg",
				scrollToId: '',
				testList: [{
						replayText: "爸爸",
					},
					{
						replayText: "乖儿子，咋了?",
						my: true
					},

				]
			}
		},
		watch: {
			keyBordHeight: {
				handler(newVal, oldVal) {
					if (newVal) {
						this.bgBoxHeight = newVal + this.inputContentHeight
					}
				},
				deep: true,
				immediate: true
			},
			messageText: {
				handler(newVal, oldVal) {
					if (newVal) {
						this.controlIconType = "send"
					} else {
						this.controlIconType = "more"
					}
				},
				deep: true,
				immediate: true
			},

		},

		computed: {
			moreControlIcon() {
				if (this.isMoreControlShow) {
					return "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/87af80c957544b2085737d672b4d7bf1.png"
				} else {
					return "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/57d2960d3f4a45f8964ad63d433a7f96.png"
				}
			}
		},
		created() {
			try {
				let screenWidth = uni.getStorageSync('screenWidth')
				if (screenWidth) {
					this.screenWidth = screenWidth
				} else {
					this.screenWidth = uni.getSystemInfoSync().screenWidth; // 当前设备屏幕宽度
					uni.setStorageSync("screenWidth", this.screenWidth)
				}
				let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
				let {
					top,
					height
				} = menuButtonInfo
				this.topBoxHeight = this.pxToRpx(top + height) + 10
			} catch (error) {
				//TODO handle the exception
			}
		},
		mounted() {
			this.scrollToBottom() //暂时性 需要在初始化完毕后再滚动

			if (this.agentId) {
				this.handleChatInit()
			} else {
				let waitNum = 0
				let interValId = setInterval(() => {
					if (waitNum >= 20) {
						clearInterval(interValId)
					}
					if (this.agentId) {
						clearInterval(interValId)
						this.handleChatInit()
					} else {
						waitNum++
					}
				}, 50)
			}


		},
		methods: {
			pxToRpx(px) {
				const designWidth = 750; // 设计稿宽度
				const rpx = (designWidth / this.screenWidth) * px; // 根据屏幕宽度计算 rpx
				return rpx;
			},
			// 接口相关
			handleChatInit() {
				let gameId = this.gameId
				let roleAgentId = this.agentId
				chatInit({
					gameId,
					roleAgentId
				}).then(res => {
					this.gameChat = res.data.result
					// this.chatId = this.gameChat.id
					this.params.chatId = this.gameChat.id
					this.handleGetChatMessageList()
				})

			},
			handleGetChatMessageList() {
				getChatMessageList(this.params).then(res => {
					// console.log("获取消息列表", res);
					let result = res.data.result;
					if (res.data.success && result && result.length > 0) {
						this.params.pageNumber = this.params.pageNumber + 1;
						let targets = result.map((item) => {
							if (item.fromUser === this.gameChat.memberId) {
								item.my = true;
							}
							return item;
						});
						this.msgList.unshift(...targets);
						// console.log("列表是", this.msgList);
						// 滚动到底部
						this.scrollToBottom()
					}
				})
			},
			// 输入框逻辑
			inputConfirmMessage() {
				if (!this.messageText) {
					return false;
				}
				let message = this.messageText

				let chatMessage = {
					gameChatId: this.gameChat.id,
					toUser: this.gameChat.agentId,
					fromUser: this.gameChat.memberId,
					gameId: this.gameId,
					storyId: this.storyId,
					messageType: 'MESSAGE',
					text: message,
				};

				this.msgList.push({
					text: message,
					replyText: message,
					my: true,
					messageType: 'MESSAGE',
				});
				this.messageText = ""
				this.scrollToBottom()
				sentMessage(chatMessage).then((res) => {
					if (res.data.success) {
						let result = res.data.result;
						this.setMessage(result);
					}
				});

			},
			setMessage(results) {
				// this.msgLoad = false = false;
				let resLength = results.length
				if (!resLength) {
					// this.msgLoad = false
				} else {}
				const insertMessage = (index) => {
					if (index < results.length) {
						const result = results[index];
						this.msgList.push(result);
						// this.msgLoad = false
						this.scrollToBottom()
						let nextResult = results[index + 1]
						// if (nextResult) {
						// 	setTimeout(() => {
						// 		this.msgLoad = true
						// 	}, 200)
						// }
						// 随机生成下一条消息的插入延迟时间（1-3秒） 第一句本来就不延迟
						// const delay = 1000 + Math.floor(Math.random() * 2000);
						let delay = 1000
						if (nextResult && nextResult.messageType == 'MESSAGE') { //这样子控制的是吓一跳消息的时间，而不是本条消息的时间
							let length = nextResult.text.length
							if (length < 4) {
								delay = 1000
							} else {
								let num1 = length / 4
								let num2 = length % 4
								delay = (num2 === 0) ? num1 * 1000 : (num1 + 1) * 1000
							}

						}

						if (index == results.length - 1) {
							// this.msgLoad = false; //关闭等待

						}
						setTimeout(() => insertMessage(index + 1), delay);
					}
				};

				// 开始插入消息
				insertMessage(0);
			},
			inputBlur() {
				setTimeout(() => {
					if (!this.isShowMagic && !this.isMoreControlShow) {
						this.inputIsFocus = false
						this.isMoreControlShow = false
						this.keyBordHeight = 0
					}
				}, 0)

			},
			inputFocus() {
				this.isMoreControlShow = false
				this.isShowMagic = false
			},
			handleKeyBoardHeightChange(e) {
				if (e.detail.height) {
					let rpxHeight = this.pxToRpx(e.detail.height)
					this.keyBordHeight = rpxHeight
				} else {
					// this.isMoreControlShow = false
					// this.keyBordHeight = 0
				}
				this.scrollToBottom()
			},
			// 魔法棒逻辑
			handleMagicIconClick() {
				this.isShowMagic = !this.isShowMagic
				if (this.isShowMagic) {
					this.isMoreControlShow = false
					this.buttonBoxHeight = 500
					this.keyBordHeight = 500
				} else {
					this.keyBordHeight = 0
				}
				this.scrollToBottom()
			},

			// 更多操作按钮
			handleControlBtnClick(item, index) {
				if (this.clickTimeOutId) {
					return
				}
				this.actClickIndex = index
				this.clickTimeOutId = setTimeout(() => {
					this.actClickIndex = -1
					clearTimeout(this.clickTimeOutId)
					this.clickTimeOutId = null
				}, 100)
			},


			// icon控制点击
			handleControlIconClick() {
				if (this.controlIconType == 'more') {
					this.isMoreControlShow = !this.isMoreControlShow
					if (this.isMoreControlShow) {
						this.buttonBoxHeight = 400
						this.keyBordHeight = 400
					} else {
						this.keyBordHeight = 0
					}
					this.scrollToBottom()
				} else if (this.controlIconType == 'send') {
					// 发送消息
					this.messageText = ""
				}
				this.isShowMagic = false

			},
			handleGlobalClick(e) {
				let targetId = e.target.id
				if (targetId && String(targetId).includes('voice')) {
					return
				}
				this.isMoreControlShow = false
				this.isShowMagic = false
				this.keyBordHeight = 0
			},

			scrollToBottom() {
				setTimeout(() => {
					this.scrollToId = ''; // 设置为一个空值
					this.$nextTick(() => {
						this.scrollToId = 'talk-item-' + String(this.msgList.length - 1)
					});
				}, 300)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.m-agent-chat {
		// background-color: #000;
		background-color: #fff;
		background-size: cover;
		background-position: center center;
		background-repeat: no-repeat;
		position: absolute;
		left: 0rpx;
		top: 0rpx;
		width: 100vw;
		height: 100vh;
		z-index: 999999999999999;

		.top-box {
			width: 100%;
			height: 170rpx;
		}

		.task-info {
			width: 100%;
			height: 130rpx;
			box-sizing: border-box;
			padding: 0rpx 40rpx;
			margin-bottom: 20rpx;

			.task-info-content {
				width: 100%;
				height: 100%;
				border-radius: 30rpx;
				background-image: linear-gradient(to bottom right, rgba(231, 203, 143, .9), rgba(255, 255, 255, .8));
				box-sizing: border-box;
				padding: 0rpx 30rpx;
				box-shadow: 0rpx 0rpx 4rpx rgba(0, 0, 0, .1);

				.info-top {
					width: 100%;
					margin-bottom: 20rpx;

					.info-icon {
						font-size: 22rpx;
						line-height: 22rpx;
						background-color: #3d2b27;
						height: 40rpx;
						border-radius: 20rpx;
						color: #fff;
						font-weight: 700;
						padding: 10rpx 20rpx;
						margin-right: 30rpx;
					}

					.info-round {
						.info-text {
							font-size: 20rpx;
							line-height: 20rpx;
							color: #3d2b27;
							margin-right: 10rpx;
						}

						.info-round-progress {
							position: relative;
							width: 160rpx;
							height: 25rpx;
							border-radius: 15rpx;
							background-color: #fff;

							.progress-inner {
								width: 20%;
								height: 20rpx;
								position: absolute;
								left: 2rpx;
								top: 50%;
								transform: translateY(-50%);
								background-color: #f9d57f;
								border-radius: 15rpx;
							}

							.progress-text {
								position: absolute;
								right: 10rpx;
								top: 50%;
								transform: translateY(-50%);
								font-size: 16rpx;
								line-height: 16rpx;
								color: #949292;
								z-index: 9;

							}

						}
					}
				}

				.info-target {
					width: 100%;
					font-size: 24rpx;
					line-height: 24rpx;
					color: #3d2b27;
				}
			}
		}

		.talk-log-input {
			position: relative;
			flex: 1;
			width: 100%;
			overflow: hidden;

			.talk-list-box {
				flex: 1;
				width: 100%;
				overflow: hidden;
				transition: all 0.3s linear;
				box-sizing: border-box;


				.talk-item {
					width: 100%;
					margin-bottom: 20rpx;
					box-sizing: border-box;
					padding: 0rpx 40rpx;



					.talk-item-avatar {
						width: 80rpx;
						height: 80rpx;
						border-radius: 50%;
						background-color: #fff;
						margin-right: 20rpx;
						box-shadow: 0rpx 0rpx 4rpx rgba(0, 0, 0, .1);

						.avatar-img {
							border-radius: 50%;
						}
					}

					.talk-item-text {
						position: relative;
						display: inline-block;
						border-radius: 25rpx;
						word-break: break-all;
						box-sizing: border-box;
						padding: 20rpx;
						font-size: 28rpx;
						line-height: 40rpx;
						box-shadow: 0rpx 0rpx 4rpx rgba(0, 0, 0, .1);

						.vioce-box {
							position: absolute;
							left: 0rpx;
							top: -20rpx;
							padding: 0rpx 20rpx;
							border-radius: 18rpx 18rpx 18rpx 0rpx;
							background-color: rgba(0, 0, 0, .8);
							backdrop-filter: blur(15rpx);
							z-index: 9;
							height: 40rpx;

							.voice-icon {
								width: 20rpx;
								height: 20rpx;
								margin-right: 10rpx;

							}

							.voice-text {
								font-size: 20rpx;
								line-height: 20rpx;
								color: #fff;
							}

						}
					}

					.talk-item-text-npc {
						flex: 1;
						background-color: rgba(0, 0, 0, .8);
						backdrop-filter: blur(15rpx);
						color: #fff;
						margin-top: 20rpx;
					}

					.talk-item-text-intro {
						flex: 1;
						background-color: rgba(0, 0, 0, .6);
						backdrop-filter: blur(15rpx);
						font-size: 26rpx;
						color: #fff;
						letter-spacing: 3rpx;
						padding: 30rpx;

						.intro-tip-text {
							color: rgba(255, 255, 255, .6);
						}
					}

					.talk-item-text-user {
						background-color: rgba(255, 255, 255, .95);
						color: #383831;
					}
				}
			}

			.input-box {
				position: relative;
				// position: absolute;
				// left: 0rpx;
				// bottom: 0rpx;
				width: 100%;
				height: 120rpx;
				transition: all 0.1s linear;
				box-sizing: border-box;
				padding: 0rpx 20rpx;

				.input-content {
					position: relative;
					width: 100%;
					height: 80rpx;
					z-index: 9;

					.input-area {
						flex: 1;
						height: 80rpx;
						// border-radius: 40rpx;
						border-radius: 20rpx;
						background-color: rgba(255, 255, 255, .6);
						backdrop-filter: blur(15rpx);
						margin-right: 10rpx;

						.input-area-inner {
							flex: 1;
							height: 100%;
							margin-left: 20rpx;

							.input-inner {
								width: 100%;
								height: 100%;
								background-color: transparent;
								font-size: 28rpx;
								line-height: 28rpx;
								color: #fff;
							}





						}

						.input-magic-icon {
							width: 65rpx;
							height: 65rpx;
							margin-right: 10rpx;
							margin-left: 10rpx;
						}


					}

					.input-control-icon {
						width: 80rpx;
						height: 80rpx;

						.input-add-icon {
							width: 65rpx;
							height: 65rpx;
							transform: rotate(0deg);
							transition: all 0.5s linear;
						}

						.control-icon-rotate {
							transition: all 0.5s linear;
							transform: rotate(45deg);
						}

						.input-send-icon {
							width: 65rpx;
							height: 65rpx;
							background-color: #fcd887;
							border-radius: 50%;
						}
					}
				}

				.input-bg-box {
					position: absolute;
					left: 0rpx;
					top: 0rpx;
					width: 100%;
					z-index: 2;

					.bg-top-box {
						width: 100%;
						height: 100rpx;
						background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0)0%, rgba(0, 0, 0, .6)60%, rgba(0, 0, 0, .8)100%);
					}

					.bg-bottom-box {
						width: 100%;
						flex: 1;
						background-color: rgba(0, 0, 0, .8);
						backdrop-filter: blur(15rpx);
					}

				}

				.input-operate-box {
					position: absolute;
					left: 0rpx;
					width: 100%;
					z-index: 3;

					.operate-tip {
						width: 100%;
						box-sizing: border-box;
						padding: 0rpx 30rpx;
						font-size: 24rpx;
						line-height: 24rpx;
						color: rgba(255, 255, 255, .6);
						margin-bottom: 20rpx;
					}

					.magic-tip-box {
						width: 100%;
						flex: 1;
						overflow: hidden;
						margin-bottom: 40rpx;

						.magic-tip-list {
							width: 100%;
							height: 100%;
							box-sizing: border-box;
							padding: 0rpx 30rpx;


							.magic-tip-item {
								width: 100%;
								border-radius: 20rpx;
								background-color: rgba(255, 255, 255, .1);
								word-break: break-all;
								box-sizing: border-box;
								padding: 20rpx;
								font-size: 28rpx;
								line-height: 40rpx;
								color: #fff;
								margin-bottom: 20rpx;
							}
						}
					}

				}

				.input-control-btns {
					position: absolute;
					left: 0rpx;
					width: 100%;
					z-index: 3;

					.control-btn-list-box {
						width: 630rpx;
						height: 100%;
						flex-wrap: wrap;
						padding-top: 20rpx;
						padding-bottom: 40rpx;

						.control-btn-list {
							width: 100%;
							flex-wrap: wrap;
						}

						.control-btn-item {
							position: relative;
							width: 120rpx;
							height: 120rpx;
							background-color: rgba(255, 255, 255, .1);
							margin-right: 50rpx;
							margin-bottom: 50rpx;
							border-radius: 10rpx;


							&:nth-child(4n) {
								margin-right: 0rpx;
							}

							.btn-icon {
								width: 60rpx;
								height: 60rpx;
							}

							.btn-name {
								position: absolute;
								left: 0rpx;
								bottom: -40rpx;
								width: 100%;
								height: 30rpx;
								font-size: 24rpx;
								line-height: 24rpx;
								color: #fff;
								text-align: center;
							}
						}
					}
				}




			}
		}
	}

	.click-style {
		animation: buttonClickScale 0.1s ease-in-out;
	}
</style>